package com.fulihui.systemcore.service;

import com.fulihui.systemcore.api.SysColumnService;
import com.fulihui.systemcore.dal.dataobj.SysColumn;
import com.fulihui.systemcore.dal.dataobj.SysColumnExample;
import com.fulihui.systemcore.dto.SysColumnDTO;
import com.fulihui.systemcore.enums.ColumnStatusEnum;
import com.fulihui.systemcore.repository.SysColumnRepository;
import com.fulihui.systemcore.request.column.CreateSysColumnRequest;
import com.fulihui.systemcore.request.column.SysColumnIdRequest;
import com.fulihui.systemcore.request.column.SysColumnQueryRequest;
import com.fulihui.systemcore.request.column.UpdateSysColumnRequest;
import com.google.common.collect.Lists;
import org.apache.dubbo.config.annotation.Service;
import org.near.servicesupport.error.Errors;
import org.near.servicesupport.result.*;
import org.near.servicesupport.util.ServiceAssert;
import org.near.toolkit.common.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

import static org.near.servicesupport.result.ResultBuilder.succ;
import static org.near.servicesupport.result.ResultBuilder.succTSingle;

/**
 *
 * @author ssm 2018年2月27日 下午12:06:26
 */
@Service(version = "1.0.0")
public class SysColumnServiceImpl implements SysColumnService {
    private final transient Logger LOG = LoggerFactory.getLogger(getClass());
    @Autowired
    private SysColumnRepository sysColumnRepository;

    @Override public BaseResult create(CreateSysColumnRequest request) {
        ServiceAssert.notNull(request, Errors.Commons.REQUEST_PARAMETER_ERROR);
        ServiceAssert.notNull(request.getLevel(), Errors.Commons.REQUEST_PARAMETER_ERROR);
        SysColumnDTO dto = new SysColumnDTO();
        dto.setLevel(request.getLevel());
        dto.setStopDate(request.getStopDate());
        dto.setParentId(request.getParentId());
        dto.setName(request.getName());
        dto.setImg(request.getImg());
        dto.setSort(request.getSort());
        dto.setStartDate(request.getStartDate());
        dto.setUrl(request.getUrl());
        Date date = new Date();
        dto.setCreateDate(date);
        dto.setUpdateDate(date);
        dto.setStatus(ColumnStatusEnum.NEW.getCode());
        dto.setKeyName(request.getKeyName());
        sysColumnRepository.insert(dto);
        return succ();
    }

    @Override public BaseResult update(UpdateSysColumnRequest request) {
        ServiceAssert.notNull(request, Errors.Commons.REQUEST_PARAMETER_ERROR);
        ServiceAssert.notNull(request.getId(), Errors.Commons.REQUEST_PARAMETER_ERROR);
        SysColumnDTO dto = new SysColumnDTO();
        dto.setId(request.getId());
        dto.setStopDate(request.getStopDate());
        dto.setName(request.getName());
        dto.setImg(request.getImg());
        dto.setSort(request.getSort());
        dto.setStartDate(request.getStartDate());
        dto.setUrl(request.getUrl());
        Date date = new Date();
        dto.setUpdateDate(date);
        dto.setStatus(request.getStatus());
        dto.setKeyName(request.getKeyName());
        LOG.info("SysColumnDTO:{}",dto.toString());
        sysColumnRepository.updateValue(dto);
        return succ();
    }

    @Override public TPageResult<SysColumnDTO> queryPage(SysColumnQueryRequest request) {
        ServiceAssert.notNull(request, Errors.Commons.REQUEST_PARAMETER_ERROR);
        SysColumnExample example = getSysColumnExample(request);
        int count = sysColumnRepository.queryPageCount(example);
        int page = request.getPage();
        int rows = request.getRows();
        if(page > 0 || rows > 0){
            example.setLimit(rows);
            example.setOffset(request.start4Mysql());
        }
        example.setOrderByClause("sort DESC,create_date DESC");

        List<SysColumnDTO> list = sysColumnRepository.query(example);

        if (CollectionUtils.isEmpty(list)) {
            return ResultBuilder
                    .succTPage(Lists.newArrayList(), request.getPage(), request.getRows(), 0);
        }

        return ResultBuilder.succTPage(list, request.getPage(), request.getRows(), count);
    }



    @Override
    public TMultiResult<SysColumnDTO> query(SysColumnQueryRequest request) {
        ServiceAssert.notNull(request, Errors.Commons.REQUEST_PARAMETER_ERROR);

        SysColumn sysColumn = new SysColumn();
        if(request.getLevel() != null){
            sysColumn.setLevel(request.getLevel());
        }
        if(request.getOnDate() != null){
            sysColumn.setStartDate(request.getOnDate());
        }
        if(request.getStatus() != null){
            sysColumn.setStatus(request.getStatus());
        }
        if(request.getParentId() != null){
            sysColumn.setParentId(request.getParentId());
        }
        List<SysColumnDTO> list = sysColumnRepository.query(sysColumn);

        if (CollectionUtils.isEmpty(list)) {
            return ResultBuilder
                    .succTMulti(Lists.newArrayList());
        }

        return ResultBuilder.succTMulti(list);
    }

    @Override public BaseResult updateStatus(SysColumnIdRequest request) {
        ServiceAssert.notNull(request, Errors.Commons.REQUEST_PARAMETER_ERROR);
        ServiceAssert.notNull(request.getId(), Errors.Commons.REQUEST_PARAMETER_ERROR);
        ServiceAssert.notNull(request.getStatus(), Errors.Commons.REQUEST_PARAMETER_ERROR);
        SysColumnDTO sysColumnDTO = sysColumnRepository.queryById(request.getId());
        String status = request.getStatus();
        Long level = sysColumnDTO.getLevel();
        SysColumnDTO sysColumnUpdate = new SysColumnDTO();
        sysColumnUpdate.setId(sysColumnDTO.getId());
        sysColumnUpdate.setStatus(status);

        if(level == 1L) {
            if (ColumnStatusEnum.ONLINE.getCode().equals(status)) {
                //上线
                sysColumnRepository.updateValue(sysColumnUpdate);
            } else if (ColumnStatusEnum.OFFLINE.getCode().equals(status)) {
                //下线
                SysColumnExample example = new SysColumnExample();
                SysColumnExample.Criteria criteria = example.createCriteria();
                criteria.andParentIdEqualTo(sysColumnDTO.getId());
                List<SysColumnDTO> list = sysColumnRepository.query(example);
                if(CollectionUtils.isEmpty(list)){
                    sysColumnRepository.updateValue(sysColumnUpdate);
                }else{
                   return ResultBuilder.fail(101,"当前类目下还有二级类目");
                }


            }
        }else if(level == 2L){
            sysColumnRepository.updateValue(sysColumnUpdate);
        }
        return succ();
    }

    @Override public TSingleResult<SysColumnDTO> queryByPk(SysColumnIdRequest request) {
        ServiceAssert.notNull(request, Errors.Commons.REQUEST_PARAMETER_ERROR);
        ServiceAssert.notNull(request.getId(), Errors.Commons.REQUEST_PARAMETER_ERROR);
        SysColumnDTO sysColumnDTO = sysColumnRepository.queryById(request.getId());
        LOG.info("SysColumnDTO:{}",sysColumnDTO.toString());
        return succTSingle(sysColumnDTO);
    }


    @Override public BaseResult delete(SysColumnIdRequest request) {
        ServiceAssert.notNull(request, Errors.Commons.REQUEST_PARAMETER_ERROR);
        Long parentId = request.getParentId();
        Long id = request.getId();
        if(id != null){
            sysColumnRepository.delete(id);
        }
        if(parentId != null){
            sysColumnRepository.deleteByParentId(parentId);
        }

        return succ();
    }
    
    
    public SysColumnExample getSysColumnExample(SysColumnQueryRequest request){
        SysColumnExample example = new SysColumnExample();
        SysColumnExample.Criteria criteria = example.createCriteria();
        Long parentId = request.getParentId();
        if(parentId != null){
            criteria.andParentIdEqualTo(parentId);
        }
        Long level = request.getLevel();
        if(level != null){
            criteria.andLevelEqualTo(level);
        }
        String status = request.getStatus();
        if(StringUtil.isNotEmpty(status)){
            criteria.andStatusEqualTo(status);
        }
        Date onDate = request.getOnDate();
        if(onDate != null){
            criteria.andStartDateLessThanOrEqualTo(onDate);
            criteria.andStopDateGreaterThanOrEqualTo(onDate);
        }
        return example;
    }
    
}